<template>
<div>
  <div class="calendar_container">
    <div class="selectMonth">
      <span @click="forwardMonth">上月</span>
      <span>{{ theMonthShow }}</span>
      <span @click="nextMonth">下月</span>
    </div>
    <div class="calendar_title">
      <div class="calendar_title_item">周日</div>
      <div class="calendar_title_item">周一</div>
      <div class="calendar_title_item">周二</div>
      <div class="calendar_title_item">周三</div>
      <div class="calendar_title_item">周四</div>
      <div class="calendar_title_item">周五</div>
      <div class="calendar_title_item">周六</div>
      <!-- <span class="leftArrow icon iconfont iconfontyoujiantou" @click="forwardMonth"></span>
      <span class="rightArrow icon iconfont iconfontyoujiantou" @click="nextMonth"></span> -->
    </div>
    <div class="calendar_wrapper">
      <div class="calendar_line clear">
        <div :class="{calendar_line_item:true, active:item.activeClass=='1',hasLesson: item.hasLesson, others:item.activeClass=='3'}"
        v-for="(item, index) in daysList" :key="index"
        @click="clickDay(item, index)"
        >{{ item.date }}</div>
      </div>
    </div>
  </div>
</div>
</template>

<script>
import { Toast } from 'vant'
import { getCookieStorage, setCookieStorage, getFormateDate } from '@/assets/js/common.js'
export default {
  data () {
    return {
      courseYM: getFormateDate(new Date(), 'yyyyMM'),
      userId: getCookieStorage('userInfo').id,
      courseLogList: [],
      userType: getCookieStorage('userType'),
      // --------------
      daysList: [],
      // 当月的1号是星期几
      firstDayWeek: '',
      theMonthIndex: '',
      theDaysOfMonth: [],
      // 日历头部月份显示
      theMonthShow: getFormateDate(new Date(), 'yyyy/MM'),
      selectDayAndDays: [getFormateDate(new Date(), 'yyyy/MM/dd')]
    }
  },
  mounted () {
    this.getTheDaysOfMonth()
    // 合并日历和课程
    this.getAllDaysInfo()
    this.getStusLogList()
    this.$emit('listenToCalendar', [getFormateDate(new Date(), 'yyyy/MM/dd')])
  },
  methods: {
    // 获取当月课程列表
    getStusLogList () {
      let url = ''
      if (this.userType === '学生') {
        url = '/api/course/getStudentCourseLogList'
      } else if (this.userType === '老师') {
        url = '/api/course/getTeacherCourseLogList'
      }
      this.$api.post(url,
        {
          userId: this.userId,
          courseYM: Number(this.courseYM)
        }).then(res => {
        if (res.code === 0) {
          this.courseLogList = res.data.courseLogList
          if (!this.courseLogList) {
            Toast({
              message: '无该月相关课程',
              position: 'bottom'
            })
            return
          }
          setCookieStorage('courseLogList', this.courseLogList)
          for (var i = 0; i < this.daysList.length; i++) {
            for (var j = 0; j < this.courseLogList.length; j++) {
              // console.log(this.courseLogList[j].startDate.match(/-(\d+) /)[1])
              if (this.daysList[i].week && this.courseLogList[j].startDate && Number(this.daysList[i].date) === Number(this.courseLogList[j].startDate.match(/-(\d+) /)[1])) {
                // console.log('haslesson')
                this.$set(this.daysList, i, {
                  activeClass: this.daysList[i].activeClass,
                  date: this.daysList[i].date,
                  id: this.daysList[i].id,
                  week: this.daysList[i].week,
                  hasLesson: true
                })
              }
            }
          }
        }
      })
    },
    // 多选日期
    clickDay (item, index) {
      if (item.activeClass === '3') {
        if (item.date > 15) {
          this.forwardMonth()
        } else {
          this.nextMonth()
        }
      } else {
        this.daysList.forEach((item, index) => {
          if (item.id && item.activeClass) {
            item.activeClass = '2'
          }
        })
        this.$set(this.daysList, index, {
          activeClass: '1',
          date: item.date,
          id: item.id,
          hasLesson: item.hasLesson,
          week: item.week
        })
        if (item.date < 10) {
          item.date = '0' + item.date
        }
        this.selectDayAndDays = [this.theMonthShow + '/' + item.date]
        this.$emit('listenToCalendar', this.selectDayAndDays)
      }
    },
    // this.selectDayAndDays里面是否有选中的日期 如果有则返回下标加1。。。反之。。。返回false
    isSetSelectDate (item) {
      for (var j in this.selectDayAndDays) {
        if (this.selectDayAndDays[j] === this.theMonthShow + '/' + item.date) {
          return j + 1
        }
      }
      return false
    },
    // 点击左箭头
    forwardMonth () {
      // var currentDate = new Date()
      // var currentYear = currentDate.getFullYear()
      // var currentMonth = currentDate.getMonth() + 1
      var selectYear = Number(this.theMonthShow.split('/')[0])
      var selectMonth = Number(this.theMonthShow.split('/')[1])
      // if (selectYear > currentYear) {
      selectMonth--
      if (selectMonth === 0) {
        selectMonth = 12
        selectYear--
      }
      // }
      // else if (selectYear === currentYear) {
      //   if (selectMonth > currentMonth) {
      //     selectMonth--
      //   } else {
      //     Toast({
      //       message: '不能再往前了',
      //       duration: 2000,
      //       position: 'bottom'
      //     })
      //   }
      // }
      this.theMonthShow = selectYear + '/' + (selectMonth < 10 ? '0' + selectMonth : selectMonth)
      this.getTheDaysOfMonth(this.theMonthShow)
      this.getAllDaysInfo()
      this.$emit('changeMonth', this.theMonthShow)
      // 点击上月
      this.courseYM = this.theMonthShow.replace(/\//, '')
      this.getStusLogList()
    },
    // 点击右箭头
    nextMonth () {
      var year = Number(this.theMonthShow.split('/')[0])
      var month = Number(this.theMonthShow.split('/')[1])
      month++
      if (month === 13) {
        month = 1
        year++
      }
      this.theMonthShow = year + '/' + (month < 10 ? '0' + month : month)
      this.getTheDaysOfMonth(this.theMonthShow)
      this.getAllDaysInfo()
      this.$emit('changeMonth', this.theMonthShow)
      // 点击下月
      this.courseYM = this.theMonthShow.replace(/\//, '')
      this.getStusLogList()
    },
    // 获取当月的每一天的信息 date:2018/7
    getTheDaysOfMonth (date) {
      // 每执行一次此函数都要把之前的清理掉
      this.daysList = []
      var currentDate = new Date()
      // 判断今年是否为闰年
      var fullYear = currentDate.getFullYear()
      date = date || fullYear.toString() + '/' + (currentDate.getMonth() + 1)
      // 今年的每月多少天list
      var daysOfMonth = [31, this.isLeapYear(fullYear) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
      // 获取(当前)月份在上述list中的下标加1
      var monthIndex = date.split('/')[1]
      // 获取(当前)月份的第一天是星期几
      // Wed Jul 11 2018 13:58:36 GMT+0800 (中国标准时间)
      var nowDayArr = new Date().toString().split(' ')
      // 下面两个变量在getAllDaysInfo方法中会用到
      this.theMonthIndex = monthIndex - 1
      this.theDaysOfMonth = daysOfMonth
      nowDayArr[1] = monthIndex
      nowDayArr[2] = '1'
      // console.log(nowDayArr.join(' '))
      // 猜测此行有兼容性问题
      // var firstDay = new Date(nowDayArr.join(' '))
      // 替代
      // console.log(date.split('/')[0])
      var firstDay = new Date(new Date().setFullYear(date.split('/')[0], this.theMonthIndex, 1))
      // 0 1 2 3 4 5 6
      var firstDayWeek = firstDay.getDay()
      // console.log(firstDayWeek)
      this.firstDayWeek = firstDayWeek
      // 动态添加当月的信息到this.daysList
      for (var i = 1; i < daysOfMonth[monthIndex - 1] + 1; i++) {
        var activeClass = '2'
        // 星期与日期对应
        if (firstDayWeek === 7) {
          firstDayWeek = 0
        }
        // 是否当天，当天为1，当月的非当天的为2，非当月的为3
        if (currentDate.getDate() === i && monthIndex === (currentDate.getMonth() + 1).toString()) {
          activeClass = '1'
        } else {
          activeClass = '2'
        }
        this.daysList.push({
          id: i,
          date: i.toString(),
          week: firstDayWeek.toString(),
          hasLesson: false,
          activeClass: activeClass
        })
        firstDayWeek++
      }
    },
    // 获取页面展示那一页的所有天数的信息
    getAllDaysInfo () {
      var forwardMonthLen = this.firstDayWeek
      console.log(forwardMonthLen)
      var nextMonthLen = 7 - this.daysList.length % 7 - forwardMonthLen
      // 添加前面的天数
      var forwardDays = this.theDaysOfMonth[this.theMonthIndex - 1] || 31
      if (nextMonthLen < 0) {
        // 考虑到此月份的一头一尾都有空余的日期格子
        nextMonthLen = 14 - this.daysList.length % 7 - forwardMonthLen
      }
      for (var j = forwardDays; j > forwardDays - forwardMonthLen; j--) {
        var item = ({
          date: j.toString(),
          week: '',
          activeClass: '3'
        })
        this.daysList.unshift(item)
      }
      // 添加后面的天数
      for (var i = 1; i <= nextMonthLen; i++) {
        this.daysList.push({
          date: i.toString(),
          week: '',
          activeClass: '3'
        })
      }
    },
    // 判断是否为闰年
    isLeapYear (fullYear) {
      if (fullYear % 4 === 0 && (fullYear % 100 !== 0 || fullYear % 400 === 0)) {
        return true
      } else {
        return false
      }
    }
  },
  components: {
    Toast
  }
}
</script>

<style lang="scss" scoped>
  .calendar_container {
    padding: 0 .2rem;
    padding-bottom: .1rem;
    background: #f0f0f6;
    .selectMonth {
      background: #fff;
      margin: 0 -.2rem;
      padding: .1rem .2rem;
      display: flex;
      justify-content: space-between;
      span {
        color: #999;
        border: 1px solid #efefef;
        padding: 4px 8px;
        border-radius: 5px;
      }
    }
    .showWrapper {
      background: #fff;
    }
    .calendar_title {
      padding: .05rem 0;
      &::after {
        content: '';
        clear: both;
        display: block;
      }
      .calendar_title_item {
        color: #000;
        width: .47rem;
        height: .3rem;
        float: left;
        line-height: .3rem;
        text-align: center;
        border: 1px solid transparent;
        margin-top: 0;
      }
      // .leftArrow, .rightArrow {
      //   display: block;
      //   position: absolute;
      //   top: .09rem;
      //   width: .08rem;
      //   height: .14rem;
      //   background-size: 100% 100%;
      //   background-repeat: no-repeat;
      // }
      // .leftArrow {
      //   left: -3px;
      //   // background-image: url('../assets/images/left.png');
      // }
      // .rightArrow {
      //   right: -3px;
      //   // background-image: url('../assets/images/right.png');
      // }
    }
    .calendar_wrapper {
      &:after {
        content: '';
        display: block;
        clear: both;
      }
      .calendar_line {
        &:after {
          content: '';
          display: block;
          clear: both;
        }
        .calendar_line_item {
          float: left;
          width: .47rem;
          height: .47rem;
          background: #fff;
          line-height: .47rem;
          border: 1px solid #efefef;
          text-align: center;
          color: #000;
          position: relative;
          // margin: .02rem;
          &.active {
            background: #009bff;
            color: #fff;
            // border: 1px solid #009bff;
          }
          &.others {
            color: #c4c9d6;
          }
          &.hasLesson:after {
            content: '';
            display: block;
            width: 6px;
            height: 6px;
            background: orange;
            border-radius: 50%;
            position: absolute;
            top: 4px;
            left: 4px;
          }
        }
      }
    }
  }
</style>
